package com.sls.nzdapplication.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.TableData;
import com.esri.arcgisruntime.geometry.GeodeticCurveType;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.LinearUnit;
import com.esri.arcgisruntime.geometry.LinearUnitId;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.PolylineBuilder;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.ess.filepicker.FilePicker;
import com.ess.filepicker.model.EssFile;
import com.ess.filepicker.util.Const;
import com.hmy.popwindow.PopItemAction;
import com.hmy.popwindow.PopWindow;
import com.markfrain.formview.view.FormEditView;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.AppActivity;
import com.sls.nzdapplication.app.MySharedPreferences;
import com.sls.nzdapplication.db.utils.EquipmentLineUtil;
import com.sls.nzdapplication.db.utils.EquipmentUtil;
import com.sls.nzdapplication.db.utils.GyyhdUtil;
import com.sls.nzdapplication.db.utils.WorkLineUtil;
import com.sls.nzdapplication.model.DyWorkInfo;
import com.sls.nzdapplication.model.Equipment;
import com.sls.nzdapplication.model.EquipmentLine;
import com.sls.nzdapplication.model.ExportEquipment;
import com.sls.nzdapplication.model.Gyyhd;
import com.sls.nzdapplication.model.StationArea;
import com.sls.nzdapplication.model.WorkLine;
import com.sls.nzdapplication.model.ZyWorkInfo;
import com.sls.nzdapplication.myapp.ZDAPP;
import com.sls.nzdapplication.ui.custom.CableWellPhotoView;
import com.sls.nzdapplication.util.DeviceUtils;
import com.sls.nzdapplication.util.ExcelUtils;
import com.sls.nzdapplication.util.LatlonUtil;
import com.sls.nzdapplication.util.SnowFlakeUtil;
import com.sls.nzdapplication.util.Utils;
import com.sls.nzdapplication.util.UuidUtils;
import com.sls.nzdapplication.util.ZipClass;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import es.dmoral.toasty.Toasty;

/**
 * 这个类是 DyWorkActivity，是一个继承自 AppCompatActivity 的 Activity 类。这个类主要是用于中压工作的 Activity，主要包括以下功能：
 *
 * 初始化视图
 * 初始化数据
 * 显示数据
 * 新建数据
 * 打开工作
 * 删除数据
 * 选择新区域
 * */
public class ZyWorkActivity extends AppActivity implements View.OnClickListener, CableWellPhotoView.OnclickPhotoListener{
    private LinearLayout workDataView;

    private WorkLineUtil workLineUtil;

    private EquipmentLineUtil equipmentLineUtil;

    private EditText workNameView;

    private TextView startWork;

    private RadioGroup radioGroup;

    private MySharedPreferences mySharedPreferences;

    private String type = "站内";


    private static final int REQUEST_CODE_CHOOSE = 23;

    private EquipmentUtil equipmentUtil;

    private GyyhdUtil gyyhdUtil;

    PopWindow popupWindow,popupWindow3;

    CableWellPhotoView mpPhotoView,qmPhotoView;

    private String photoType;

    private boolean updatePhoto = false;

    public static final String SD_APP_DIR_NAME = "NZDAPP";

    private String autopath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/" + SD_APP_DIR_NAME + "/";


    private String zippath = autopath + "数据备份/";

    SmartTable<ZyWorkInfo> table;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_zy_work;
    }

    @Override
    protected void initView() {
        workNameView = findViewById(R.id.work_name);
        startWork = findViewById(R.id.start_zyyp);
        table = findViewById(R.id.zywork_data);
        table.getConfig().setShowXSequence(false);
        table.getConfig().setShowYSequence(false);
        table.getConfig().setShowTableTitle(false);
        table.getConfig().setColumnTitleStyle (new FontStyle(30, getResources().getColor(R.color.colorPrimaryDark)));

        workLineUtil = new WorkLineUtil(getApplicationContext());
        equipmentUtil = new EquipmentUtil(getApplicationContext());
        gyyhdUtil = new GyyhdUtil(getApplicationContext());
        equipmentLineUtil = new EquipmentLineUtil(getApplicationContext());
        mySharedPreferences = new MySharedPreferences(getApplicationContext());
        startWork.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        List<WorkLine> workLines = workLineUtil.queryAll();
        showData(workLines);
    }

    @Override
    public void onClickPhotoListener(String type) {
        photoType = type;
    }

    @Override
    public void openPhotoView(String path) {
        Intent intent = new Intent(ZyWorkActivity.this,PhotoDetailActivity.class);
        intent.putExtra("filePath",path);
        startActivity(intent);
    }

    private void newData(){
        Calendar calendar = Calendar.getInstance ();
        String name = workNameView.getText().toString();
        if(name.equals("")){
            Toasty.error(getApplicationContext(), "线路名称不能为空", Toast.LENGTH_LONG, true).show();
            return;
        }
        if(workLineUtil.queryWorkLineByAreaName(name)!=null){
            Toasty.error(getApplicationContext(), "线路名称不能重复", Toast.LENGTH_LONG, true).show();
            return;
        }
        WorkLine workLine = new WorkLine();
        workLine.setId(UuidUtils.getStringID());
        workLine.setName(name);
        workLine.setType(type);
        workLine.setCreateTime(calendar.get(Calendar.YEAR)+"年"+(calendar.get(Calendar.MONTH)+1)+"月"+calendar.get(Calendar.DATE)+"日");
        workLine.setCreateBy(mySharedPreferences.getUserValue("username"));
        workLineUtil.insertWorkLine(workLine);
        Toasty.success(getApplicationContext(), "保存成功", Toast.LENGTH_LONG, true).show();
        openWork(workLine);
    }

    private void openWork(WorkLine workLine){
        Intent intent = new Intent(ZyWorkActivity.this,ZyMapActivity.class);
        intent.putExtra("lineId",workLine.getId());
        startActivity(intent);
    }

    private void delCom(WorkLine workLine){
        new PopWindow.Builder(ZyWorkActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopUp)
                .setTitle("你确定要删除当前数据！！")
                .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        deleteData(workLine);
                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                .show();
    }


    private void deleteData(WorkLine workLine){
        List<Equipment> equipmentList = equipmentUtil.queryEquipmentByLineId(workLine.getId());
        for(Equipment equipment:equipmentList){
            equipmentUtil.deleteEquipment(equipment);
        }
        List<EquipmentLine> equipmentLineList = equipmentLineUtil.queryEquipmentLineByLineId(workLine.getId());
        for(EquipmentLine equipmentLine:equipmentLineList){
            equipmentLineUtil.deleteEquipmentLine(equipmentLine);
        }
        workLineUtil.deleteWorkLine(workLine);
        initData();
    }

    private void showData(List<WorkLine> titleData) {
        table.setTableData(null);
        List<ZyWorkInfo> zyWorkInfos = new ArrayList<>();
        for (int i = 0; i < titleData.size(); i++) {
            final WorkLine workLine = titleData.get(i);
            ZyWorkInfo zyWorkInfo = new ZyWorkInfo();
            zyWorkInfo.setId(workLine.getId());
            zyWorkInfo.setXh(String.valueOf(i+1));
            zyWorkInfo.setName(workLine.getName());
            zyWorkInfo.setBdz(String.valueOf(equipmentUtil.queryEquipmentByLineIdAndBdz(workLine.getId()).size()));
            zyWorkInfo.setGt(String.valueOf(equipmentUtil.queryEquipmentByLineIdAndGt(workLine.getId()).size()));
            zyWorkInfo.setDz(String.valueOf(equipmentUtil.queryEquipmentByLineIdAndDz(workLine.getId()).size()));
            zyWorkInfo.setKg(String.valueOf(equipmentUtil.queryEquipmentByLineIdAndKg(workLine.getId()).size()));
            zyWorkInfo.setGyb(String.valueOf(equipmentUtil.queryEquipmentByLineIdAndGyb(workLine.getId()).size()));
            zyWorkInfo.setDate(workLine.getCreateTime().toString());
            zyWorkInfos.add(zyWorkInfo);
        }
        if(zyWorkInfos.size()>0){
            table.setVisibility(View.VISIBLE);
            table.setData(zyWorkInfos);
            table.getTableData().setOnRowClickListener(new TableData.OnRowClickListener<ZyWorkInfo>() {

                @Override
                public void onClick(Column column, ZyWorkInfo zyWorkInfo, int col, int row) {
                    new PopWindow.Builder(ZyWorkActivity.this)
                            .setStyle(PopWindow.PopWindowStyle.PopUp)
                            .setTitle(titleData.get(row).getName()+"\n请选择你要的操作")
                            .addItemAction(new PopItemAction("进入线路", PopItemAction.PopItemStyle.Normal, new PopItemAction.OnClickListener(){
                                @Override
                                public void onClick() {
                                    openWork(titleData.get(row));
                                }
                            }))
                            .addItemAction(new PopItemAction("编辑", PopItemAction.PopItemStyle.Normal, new PopItemAction.OnClickListener() {
                                @Override
                                public void onClick() {
                                    editLine(titleData.get(row));
                                }
                            }))
                            .addItemAction(new PopItemAction("删除", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                                @Override
                                public void onClick() {
                                    delCom(titleData.get(row));
                                }
                            }))
                            .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                            .show();
                }
            });
        }else{
            table.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onClick(View view) {
        if(view == startWork){
            newData();
        }
    }

    @Override
    public void onRightClick(View view) {
        new PopWindow.Builder(this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("数据设置")
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("导出单个线路数据", new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        selectLine();
                    }
                }))
                .addItemAction(new PopItemAction("导出全部线路数据", new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        updateAll();
                    }
                }))
                .addItemAction(new PopItemAction("数据库备份", new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        updateHistory();
                        Toasty.success(getApplicationContext(),   "备份成功", Toast.LENGTH_LONG, true).show();
                    }
                }))
                .addItemAction(new PopItemAction("数据库备份（含照片）", new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        updatePhoto = true;
                        updateHistory();
                        Toasty.success(getApplicationContext(),   "备份成功", Toast.LENGTH_LONG, true).show();
                    }
                }))
                .addItemAction(new PopItemAction("导入历史数据包", new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {

                        pushHistory();
                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),300), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();
    }

    private void pushHistory(){
        new PopWindow.Builder(ZyWorkActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("导入历史数据将会备份当前数据")
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("确定", new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        openFile();
                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();
    }

    private void updateHistory(){
        try{
            if(workLineUtil.queryAll().size()>0){
                com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                jsonObject.put("equipment",equipmentUtil.queryAllToJson());
                jsonObject.put("workLine",workLineUtil.queryAllToJson());
                jsonObject.put("equipmentLine",equipmentLineUtil.queryAllToJson());
                jsonObject.put("gyyhd",gyyhdUtil.queryAllToJson());
                String date = SnowFlakeUtil.getStringDate();
                Utils.writeTxtToFile(jsonObject.toJSONString(),zippath+"中压/"+ date,"/dataBag.txt");
                if(updatePhoto){
                    updateHistoryPhoto(date);
                }
            }
            updatePhoto = false;
        }catch (Exception e){
            Toast.makeText(getApplicationContext(),"导出备份失败",Toast.LENGTH_LONG).show();
        }



    }

    //导出照片
    private void updateHistoryPhoto(String date){
        String nPath = zippath +"中压/"+ date+"/Equipment";
        String oPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/NZDAPP/Equipment";
        Utils.copyFolder(oPath,nPath);

        String zPath = zippath +"中压/"+ date;

        ZipClass.compressFile(zPath,  date+".zip");
    }


    private void clearData(){
        equipmentUtil.deleteAll(Equipment.class);
        workLineUtil.deleteAll(EquipmentLine.class);
    }


    private void initHistory(EssFile file) {

        if(file.getFile().getName().indexOf(".zip")>-1){
            try {
                String oPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/NZDAPP/"+file.getFile().getName();
                ZipClass.unZip(file.getFile(),oPath);
                String fPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/NZDAPP/"+file.getFile().getName()+"/"+file.getFile().getName()+"/"+"dataBag.txt";
                String date = getFileContent(new File(fPath));

                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(date);
                equipmentUtil.insertByJsArray(jsonObject.getJSONArray("equipment"));
                workLineUtil.insertByJsArray(jsonObject.getJSONArray("workLine"));
                equipmentLineUtil.insertByJsArray(jsonObject.getJSONArray("equipmentLine"));
                gyyhdUtil.insertByJsArray(jsonObject.getJSONArray("gyyhd"));
                initData();
                initPhoto(file.getFile().getName());

                Toasty.success(getApplicationContext(),   "初始化成功", Toast.LENGTH_LONG, true).show();
            }catch (Exception e){
                e.printStackTrace();
                Toasty.error(getApplicationContext(),   "导入失败", Toast.LENGTH_LONG, true).show();
            }
        }else{
            try {
                String date = getFileContent(file.getFile());
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(date);
                equipmentUtil.insertByJsArray(jsonObject.getJSONArray("equipment"));
                workLineUtil.insertByJsArray(jsonObject.getJSONArray("workLine"));
                equipmentLineUtil.insertByJsArray(jsonObject.getJSONArray("equipmentLine"));
                gyyhdUtil.insertByJsArray(jsonObject.getJSONArray("gyyhd"));
                initData();
                Toasty.success(getApplicationContext(),   "初始化成功", Toast.LENGTH_LONG, true).show();
            }catch (Exception e){
                e.printStackTrace();
                Toasty.error(getApplicationContext(),   "导入失败", Toast.LENGTH_LONG, true).show();
            }
        }



    }

    private void initPhoto(String filename){
        String nPath = autopath+ filename+"/"+filename+"/Equipment";
        String oPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/NZDAPP/Equipment";
        Utils.copyFolder(nPath,oPath);
        ZipClass.deleteDirWihtFile(new File(autopath+ filename));
        ZipClass.deleteDirWihtFile(new File(autopath+ filename+filename));
    }


    private String getFileContent(File file) {
        String content = "";
        if (!file.isDirectory()) {  //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt")) {//文件格式为""文件
                try {
                    InputStream instream = new FileInputStream(file);
                    if (instream != null) {
                        InputStreamReader inputreader
                                = new InputStreamReader(instream, "UTF-8");
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line = "";
                        //分行读取
                        while ((line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }
                        instream.close();//关闭输入流
                    }
                } catch (java.io.FileNotFoundException e) {
                    Log.d("TestFile", "The File doesn't not exist.");
                } catch (IOException e) {
                    Log.d("TestFile", e.getMessage());
                }
            }
        }
        return content;
    }

    private void updateAll(){
        List<WorkLine> workLines = workLineUtil.queryAll();

        for(WorkLine workLine:workLines){
            updateAreaDate(workLine);
        }
    }


    private void selectLine(){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,600);
        List<String> areaName = new ArrayList<>();
        ListView listView = new ListView(getApplicationContext());
        listView.setLayoutParams(layoutParams);
        List<WorkLine> workLines = workLineUtil.queryAll();

        for(WorkLine workLine:workLines){
            areaName.add(workLine.getName());
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                updateAreaDate(workLines.get(i));
//                popupWindow.dismiss();
            }
        });

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_list_item_1, areaName);
        listView.setAdapter(adapter);
        popupWindow= new PopWindow.Builder(ZyWorkActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("请选择线路")
                .addContentView(listView)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();
    }

    private void updateAreaDate(WorkLine workLine){
        exportEquipmentList(workLine);
        exportZymodel(workLine);
        Toasty.success(getApplicationContext(),   "导出成功", Toast.LENGTH_LONG, true).show();
    }

    private void exportEquipmentList(WorkLine workLine){
        try{
            List<Equipment> equipmentList = equipmentUtil.queryEquipmentByLineId3(workLine.getId());
            String[] titles = {"序号","设备名称","前端设备","所属线路","杆塔材质","设备类型","杆塔性质","杆塔型号","是否终端","经度","纬度","隐患地点","缺陷情况","数量","线路巡视检查人员","连接方式","连接线型号","连接线类型"};
            List<List<String>> dataList = new ArrayList<>();
            for(int i = 0;i<equipmentList.size();i++){
                List<String> itemData = new ArrayList<>();
                Equipment equipment = equipmentList.get(i);
                //导出照片
                copyPhoto4e(equipment,workLine.getName());

//                Map<String, Double> map =  LatlonUtil.transformGCJ2WGS(equipment.getLat(),equipment.getLon());
                Equipment exq = equipmentUtil.listOneEquipment(equipment.getPreviousEquipmentId());
                itemData.add(String.valueOf(i+1));
                itemData.add(equipment.getName());
                itemData.add(exq==null?"":exq.getName());
                itemData.add(workLine.getName());
                itemData.add(equipment.getGtcz()==null?"":equipment.getGtcz());
                itemData.add(ZDAPP.ZYEquipmentTypeName.get(equipment.getType()));
                itemData.add(equipment.getGtxz()==null?"":equipment.getGtxz());
                itemData.add(equipment.getGtxh()==null?"":equipment.getGtxh());
                itemData.add("");
                itemData.add(String.format("%.8f", equipment.getLon()));
                itemData.add(String.format("%.8f", equipment.getLat()));
                itemData.add("");
                itemData.add(equipment.getQxxx()==null?"":equipment.getQxxx());
                itemData.add("");
                itemData.add("");
                itemData.add(equipment.getLxfs()==null?"":equipment.getLxfs());
                itemData.add(equipment.getDlxh()==null?"":equipment.getDlxh());
                itemData.add(equipment.getDxlx()==null?"":equipment.getDxlx());
                dataList.add(itemData);
            }
            ExportEquipment exportEquipment = new ExportEquipment();
            exportEquipment.setFileName(workLine.getName()+"杆塔信息");
            exportEquipment.setData(dataList);
            exportEquipment.setFolderName(workLine.getName());
            exportEquipment.setTitleName(titles);
            exportExcel(getApplicationContext(),exportEquipment);
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"导出杆塔信息失败",Toast.LENGTH_LONG).show();
        }


    }


    private void copyPhoto4e(Equipment equipment,String sname){
        String nPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/NZDAPP/Equipment/"+equipment.getId()+"/";

        String ePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/NZDAPP/"+sname+"/照片/"+equipment.getType()+"/"+equipment.getName();
        String[] phototype = {"qm","mp","qx","tt","gp","gps","zsq","blq"};
        String[] photoName = {"全貌","铭牌","缺陷","塔头","钢牌","GPS定位照片","故障指示器照片","避雷器照片"};
        for(int i = 0;i<phototype.length;i++){
            List<String> files = Utils.getFilesAllName(nPath+phototype[i]+"/");
            for(int j=0;j<files.size();j++){
                System.err.println(files.get(j));
                Utils.copyFile(files.get(j),ePath+"/"+equipment.getName()+"-"+photoName[i]+(j+1)+".jpg");
            }
        }
    }

    private void copyPhoto4g(Gyyhd equipment,String sname){
        String nPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/NZDAPP/Equipment/"+equipment.getId()+"/";

        String ePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/NZDAPP/"+sname+"/照片/"+equipment.getType()+"/"+equipment.getName();
        String[] phototype = {"qm","mp","qx","tt","gp","gps","zsq","blq"};
        String[] photoName = {"全貌","铭牌","缺陷","塔头","钢牌","GPS定位照片","故障指示器照片","避雷器照片"};
        for(int i = 0;i<phototype.length;i++){
            List<String> files = Utils.getFilesAllName(nPath+phototype[i]+"/");
            for(int j=0;j<files.size();j++){
                System.err.println(files.get(j));
                Utils.copyFile(files.get(j),ePath+"/"+equipment.getName()+"-"+photoName[i]+(j+1)+".jpg");
            }
        }
    }

    //低压模板
    private void exportZymodel(WorkLine workLine){
        try{
            ExportEquipment exportEquipment = new ExportEquipment();
            exportEquipment.setFileName(workLine.getName()+"中压线路核查表("+workLine.getName()+")");
            exportEquipment.setFolderName(workLine.getName());
            exportExcelModel(getApplicationContext(),exportEquipment,workLine);
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"导出中压模板失败",Toast.LENGTH_LONG).show();
        }

    }

    //导出模板
    private void exportExcelModel(Context context, ExportEquipment exportEquipment, WorkLine workLine) {
        String autopath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/NZDAPP/"+exportEquipment.getFolderName();
        File file = new File(autopath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String excelFileName = "/"+exportEquipment.getFileName()+".xls";
        autopath = autopath + excelFileName;//文件的路径
        ExcelUtils.initExcelZY(autopath);
        ExcelUtils.writeObjListToExcel4Model(modeldataGT(workLine),autopath,0);
        ExcelUtils.writeObjListToExcel4Model(modeldataSB(workLine),autopath,1);
    }

    private String getDJ(String id){
        Equipment dyEquipment = equipmentUtil.listOneEquipment(id);
        Equipment exdyEquipment = equipmentUtil.listOneEquipment(dyEquipment.getPreviousEquipmentId());
        if(exdyEquipment.getType().equals("杆塔")){
            //坐标转换
            PolylineBuilder lineGeometry = new PolylineBuilder(SpatialReferences.getWgs84());
            lineGeometry.addPoint(new Point(dyEquipment.getLon(),dyEquipment.getLat()));
            lineGeometry.addPoint(new Point(exdyEquipment.getLon(),exdyEquipment.getLat()));
            double dis = GeometryEngine.lengthGeodetic(lineGeometry.toGeometry(), new LinearUnit(LinearUnitId.METERS), GeodeticCurveType.SHAPE_PRESERVING);

            return String.format("%.2f", dis);
        }
        return "";
    }

    private  List<List<String>> modeldataGT(WorkLine workLine){
        List<List<String>> dataList = new ArrayList<>();
        List<Equipment> equipmentList = equipmentUtil.queryEquipmentByLineIdAndGt(workLine.getId());
        for(int i = 0;i<equipmentList.size();i++){
            Equipment equipment = equipmentList.get(i);
            List<String> datas = new ArrayList<>();
            datas.add(String.valueOf(i+1));
            datas.add(equipment.getName());
            datas.add(workLine.getName());
            datas.add(equipment.getGtcz()==null?"":equipment.getGtcz());
            datas.add("中压杆塔");
            datas.add(equipment.getGtxz()==null?"":equipment.getGtxz());
            datas.add(equipment.getGtxh()==null?"":equipment.getGtxh());
            datas.add("");
            datas.add(String.format("%.8f", equipment.getLon()));
            datas.add(String.format("%.8f", equipment.getLat()));
            datas.add("");
            datas.add(equipment.getQxxx()==null?"":equipment.getQxxx());
            datas.add("");
            datas.add("");
            datas.add(getDJ(equipment.getId()));
            dataList.add(datas);
        }
        return dataList;
    }

    private  List<List<String>> modeldataSB(WorkLine workLine){
        List<List<String>> dataList = new ArrayList<>();
        List<Equipment> equipmentList = equipmentUtil.queryEquipmentByLineIdNOGtNOBdz(workLine.getId());
        for(int i = 0;i<equipmentList.size();i++){
            Equipment equipment = equipmentList.get(i);
            List<String> datas = new ArrayList<>();
            datas.add(String.valueOf(i+1));
            datas.add(equipment.getName());
            datas.add(equipment.getType());
            datas.add(equipment.getSbzt()==null?"":equipment.getSbzt());
            datas.add(workLine.getName());
            datas.add(equipment.getSbzt()==null?"":equipment.getSbzt());
            datas.add(equipment.getSbxh()==null?"":equipment.getSbxh());
            datas.add(equipment.getSbrl()==null?"":equipment.getSbrl());
            Equipment gt = equipmentUtil.listOneEquipment(equipment.getSsgt());
            if(gt!=null){
                datas.add(gt.getName());
            }
            else{
                datas.add("");
            }
            datas.add(equipment.getKgzt()==null?"":equipment.getKgzt());
            datas.add(equipment.getQxxx()==null?"":equipment.getQxxx());
            datas.add("");
            datas.add(String.format("%.8f", equipment.getLon()));
            datas.add(String.format("%.8f", equipment.getLat()));
            dataList.add(datas);
        }
        List<Gyyhd> gyyhdsList = gyyhdUtil.queryGyyhdByLineId(workLine.getId());
        for(int i = 0;i<gyyhdsList.size();i++){
            Gyyhd equipment = gyyhdsList.get(i);
            copyPhoto4g(equipment,workLine.getName());
            List<String> datas = new ArrayList<>();
            datas.add(String.valueOf(i+1));
            datas.add(equipment.getName());
            datas.add(equipment.getType());
            datas.add("");
            datas.add(workLine.getName());
            datas.add("");
            datas.add("");
            datas.add("");
            datas.add("");
            datas.add("");
            datas.add("");
            datas.add("");
            datas.add(String.format("%.8f", equipment.getLon()));
            datas.add(String.format("%.8f", equipment.getLat()));
            dataList.add(datas);
        }
        return dataList;
    }


    private void openFile(){
        FilePicker.from(this)
                .chooseForBrowser()
                .setMaxCount(3)
                .setFileTypes("txt","zip")
                .requestCode(REQUEST_CODE_CHOOSE)
                .start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_CHOOSE) {
            ArrayList<EssFile> essFileList = data.getParcelableArrayListExtra(Const.EXTRA_RESULT_SELECTION);
            boolean fileOk = true;
            String filename = "";
            updateHistory();
            clearData();
            for (EssFile file : essFileList) {
                initHistory(file);
            }
        }else{
            if(photoType.equals("qm")) {
                qmPhotoView.onActivityResultListener(requestCode, resultCode, data);
            }
            if(photoType.equals("mp")) {
                mpPhotoView.onActivityResultListener(requestCode, resultCode, data);
            }
        }
    }

    //导出
    private void exportExcel(Context context, ExportEquipment exportEquipment) {
        String autopath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/NZDAPP/"+exportEquipment.getFolderName();
        File file = new File(autopath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String excelFileName = "/"+exportEquipment.getFileName()+".xls";
        String[] title = exportEquipment.getTitleName();
        autopath = autopath + excelFileName;//文件的路径
        ExcelUtils.initExcel(autopath, exportEquipment.getFileName(),title);
        ExcelUtils.writeObjListToExcel(exportEquipment.getData(), autopath, context);
    }

    private void editLine(WorkLine workLine){
        View areaView = View.inflate(getApplicationContext(), R.layout.line_detail_layout, null);
        FormEditView areaNameView = areaView.findViewById(R.id.line_name);
        areaNameView.getContent().setText(workLine.getName());
        TextView saveAreaView = areaView.findViewById(R.id.save_line);
        saveAreaView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(areaNameView.getValue().equals("")){
                    Toasty.error(getApplicationContext(),   "线路名称不能为空", Toast.LENGTH_LONG, true).show();
                }
                else if(workLineUtil.queryWorkLineByAreaName(areaNameView.getValue())!=null && !workLineUtil.queryWorkLineByAreaName(areaNameView.getValue()).getId().equals(workLine.getId())){
                    Toasty.error(getApplicationContext(),   "该线路已存在", Toast.LENGTH_LONG, true).show();
                }else{
                    workLine.setName(areaNameView.getValue());
                    workLineUtil.updateWorkLine(workLine);
                    Toasty.success(getApplicationContext(),   "保存线路成功", Toast.LENGTH_LONG, true).show();
                }
            }
        });
        mpPhotoView = areaView.findViewById(R.id.line_mp_photo);
        qmPhotoView = areaView.findViewById(R.id.line_qm_photo);
        if(equipmentUtil.queryEquipmentByLineIdAndBdz(workLine.getId()).size()>0){
            mpPhotoView.setVisibility(View.GONE);
            qmPhotoView.setVisibility(View.GONE);
            Equipment byq = equipmentUtil.queryEquipmentByLineIdAndBdz(workLine.getId()).get(0);
            mpPhotoView.initData("Equipment",byq.getId(),"mp");
            mpPhotoView.setOnclickPhotoListener(this);
            mpPhotoView.setmActivity(ZyWorkActivity.this);
            qmPhotoView.initData("Equipment",byq.getId(),"qm");
            qmPhotoView.setOnclickPhotoListener(this);
            qmPhotoView.setmActivity(ZyWorkActivity.this);
        }else{
            mpPhotoView.setVisibility(View.GONE);
            qmPhotoView.setVisibility(View.GONE);
        }


        popupWindow3 = new PopWindow.Builder(ZyWorkActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("编辑线路内容")
                .addContentView(areaView)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("进入线路", PopItemAction.PopItemStyle.Normal, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        popupWindow3.dismiss();
                        openWork(workLine);
                    }
                }))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();
    }
}